package cn.edu.scau.info.hhb.jReflashDns;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtil {

	private IPUtil() {
	}

	public static boolean match(String ip, String regx, String regxDis) {
		if (!ip.matches(regx)) {
			return false;
		}
		if (ip.matches(regxDis)) {
			return false;
		}
		return true;
	}

	public static List<String> getAllIP() {
		List<String> lst = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> enumeration = NetworkInterface
					.getNetworkInterfaces();
			while (enumeration.hasMoreElements()) {
				NetworkInterface networkInterface = enumeration.nextElement();
				Enumeration<InetAddress> eAddr = networkInterface
						.getInetAddresses();
				while (eAddr.hasMoreElements()) {
					String ip = eAddr.nextElement().getHostAddress();
					lst.add(ip);
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lst;
	}

	public static String parseIP(String html) {
		try {
			Pattern pattern = Pattern
					.compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
			Matcher matcher = pattern.matcher(html);
			// System.out.println(html);
			if (matcher.find()) {
				// System.out.println(matcher.group());
				return matcher.group();
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}

	public static String resolveHtmlIP(String byIP) {
		try {
			SocketHttp http = new SocketHttp(byIP);
			String str = http.get("www.ip138.com", 80, "/ip2city.asp");
			return str;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
